package com.liu.stockmarket.ui.search

import android.util.Log
import androidx.lifecycle.*
import com.liu.stockmarket.model.Stock
import com.liu.stockmarket.repository.database.StockRepository
import com.liu.stockmarket.repository.database.entity.StockEntity
import com.liu.stockmarket.repository.network.EasyMoneyRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class SearchViewModel(
    private val easyMoneyRepository: EasyMoneyRepository,
    private val stockRepository: StockRepository
) : ViewModel() {

    private val _stockList = MutableLiveData<List<Stock>>()

    val stockList: LiveData<List<Stock>> = _stockList

    /**
     * 已经保存的股票
     */
    val stockListFromDB = stockRepository.all.asLiveData()


    fun doSearch(keyWord: String) {

        viewModelScope.launch(Dispatchers.IO) {
            val result = easyMoneyRepository.searchStock(keyWord)
            if (result == null) {
                _stockList.postValue(mutableListOf())
            } else {
                _stockList.postValue(result.Data)
            }
        }
    }

    fun doSave(stockEntity: StockEntity) {
        viewModelScope.launch(Dispatchers.IO) {
            stockRepository.save(stockEntity = stockEntity)
        }
    }

    fun doDelete(stockId: Long) {
        viewModelScope.launch(Dispatchers.IO) {
            stockRepository.deleteStock(stockId)
        }
    }


    class SearchViewModelFactory(
        private val easyMoneyRepository: EasyMoneyRepository,
        private val stockRepository: StockRepository
    ) :
        ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            @Suppress("UNCHECKED_CAST")
            return SearchViewModel(easyMoneyRepository, stockRepository) as T
        }

    }
}